<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          placeholder="關鍵字查詢"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <template #right>
          <el-button
            v-if="crud.optShow.add"
            v-permission="permission.add"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            :disabled="!crud.selections.length > 0"
            @click="verify"
          >
            审核
          </el-button>
        </template>
      </crudOperation>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="800px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">

          <el-form-item label="采购商品名称" prop="purchaseName">
            <el-input v-model="form.purchaseName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="upc" prop="upc">
            <el-input v-model="form.upc" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="產品編號" prop="sku">
            <el-input v-model="form.sku" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="市场价" prop="originalPrice">
            <el-input-number v-model="form.originalPrice" :min="0" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="form.price" :min="0" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="商品重量" prop="weight">
            <el-input-number v-model="form.weight" :min="0" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="產品類別" prop="purchaseProductCategoryId">
            <el-cascader
              ref="cascader"
              v-model="selectProductCateValue"
              :options="depotProductCateOptions"
              style="width: 370px;"
            />

          </el-form-item>
          <el-form-item label="庫存單位">
            <el-input v-model="form.unit" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="庫存單位數量">
            <el-input-number v-model="form.unitQuantity" :min="0" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="入庫單位">
            <el-input v-model="form.inUnit" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="入庫單位數量">
            <el-input-number v-model="form.inUnitQuantity" :min="0" style="width: 370px;" />
          </el-form-item>
          <el-col :span="12">
            <el-form-item label="是否寄售">
              <el-switch
                v-model="form.consignment"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄售是否需要取货">
              <el-switch
                v-model="form.consignmentPickUp"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        style="width: 100%;"
        stripe
        @selection-change="crud.selectionChangeHandler"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="purchaseName" label="采購商品名稱" width="300px" sortable/>
        <el-table-column prop="upc" label="UPC" sortable/>
        <el-table-column prop="sku" label="商品編號" sortable/>
        <el-table-column prop="originalPrice" label="正常售價" align="right" sortable/>
        <el-table-column prop="price" label="優惠價格" align="right" sortable/>
        <el-table-column prop="verifyStatus" label="審核狀態" sortable>
          <template slot-scope="scope">
            {{ dict.label.true_false[scope.row.verifyStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="商品重量" sortable/>
        <el-table-column prop="consignment" label="是否寄售" sortable/>
        <el-table-column prop="consignmentPickUp" label="寄售取貨" sortable/>
        <el-table-column
          v-if="checkPer(['admin','product:edit','product:del'])"
          label="操作"
          width="150px"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudProduct from '@/api/pms/product'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getTree } from '@/api/pms/productCategory'

const defaultForm = {
  originalPrice: null,
  price: null,
  purchaseProductCategoryId: null,
  verifyStatus: false,
  purchaseName: null,
  weight: null,
  upc: null,
  sku: null,
  consignment: false,
  consignmentPickUp: false,
  unit: null, // 庫存單位
  unitQuantity: null, // 庫存單位數量
  inUnit: null, // 入庫單位
  inUnitQuantity: null // 入庫單位數量

}
export default {
  name: 'WarehouseProduct',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['activeType', 'true_false'],
  cruds() {
    return CRUD({ title: '商品', url: 'product/page', sort: 'id:desc', crudMethod: { ...crudProduct }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'depotProduct:add'],
        edit: ['admin', 'depotProduct:edit'],
        del: ['admin', 'depotProduct:del'],
        verify: ['admin', 'depotProduct:verify']
      },
      rules: {
        purchaseName: [
          { required: true, message: '請填寫採購商品名稱', trigger: 'blur' }
        ],
        originalPrice: [
          { required: true, message: '請填寫市場價', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '請填寫價格', trigger: 'blur' }
        ],
        sku: [
          { required: true, message: '請填寫產品編號', trigger: 'blur' }
        ],
        upc: [
          { required: true, message: '請填寫upc', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '請填寫商品重量', trigger: 'blur' }
        ],
        purchaseProductCategoryId: [
          { required: true, message: '請選擇產品類別', trigger: 'change' }
        ]
      },
      depotProductCateOptions: [],
      selectProductCateValue: [],
      queryTypeOptions: [
        { key: 'nameCn', display_name: '中文商品名称' },
        { key: 'nameEn', display_name: '英文商品名称' }
      ]
    }
  },
  watch: {
    selectProductCateValue: function(newValue) {
      if (newValue != null && newValue.length === 2) {
        this.form.purchaseProductCategoryId = newValue.slice(-1).join()
      } else {
        this.form.purchaseProductCategoryId = null
      }
    }
  },
  created() {
    this.getProductCategory()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getProductCategory() {
      getTree().then(response => {
        const list = response.data
        this.depotProductCateOptions = []
        for (let i = 0; i < list.length; i++) {
          const children = []
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ value: list[i].children[j].id, label: list[i].children[j].label })
            }
          }
          this.depotProductCateOptions.push({ value: list[i].id, label: list[i].label, children: children })
        }
      })
    },
    verify() {
      const productIds = this.crud.selections.map(item => { return item.id })
      crudProduct.audit({ productIds: productIds, verifyStatus: 1 }).then(res => {
        this.$notify({
          title: res.code === 0 ? '成功' : '失敗',
          message: res.message,
          type: res.code === 0 ? 'success' : 'error'
        })
        this.crud.refresh()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    sortChange(column) {
      const sortColumn = column.prop
      if (column.order === 'ascending') {
        this.crud.sort = [sortColumn + ':asc']
      }
      if (column.order === 'descending') {
        this.crud.sort = [sortColumn + ':desc']
      }
      this.crud.refresh()
    }
  }
}
</script>

<style scoped>

</style>
